import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  View,
  Linking,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Image } from 'expo-image';
import { Ionicons } from '@expo/vector-icons';
import AntDesign from '@expo/vector-icons/AntDesign';
import { Stack, useLocalSearchParams, useRouter } from 'expo-router';

import { useAuth } from '@/context/auth-context';
import { apiRequest, apiRequestWithMeta, ApiError } from '@/utils/api';
import { resolveAssetUrl, API_ORIGIN } from '@/constants/config';
import { addHistory } from '@/utils/history';
import { addFavorite, removeFavorite, isFavorite } from '@/utils/favorites';
import { encodeRedirectParam } from '@/utils/redirect';
import { getLastPayChannel, PayChannel } from '@/utils/pay';
import { PageHeader } from '@/components/page-header';

type ApiAsset = {
  id: number;
  preview_url?: string;
  thumb_url?: string;
  original_url?: string;
};

type ApiProductImage = {
  id: number;
  sort_order: number;
  is_preview?: boolean;
  asset?: ApiAsset | null;
};

type ApiProduct = {
  id: number;
  title: string;
  type: string;
  description: string;
  price: number;
  promo_price?: number;
  promo_expires_at?: string;
  cover_asset?: ApiAsset | null;
  images?: ApiProductImage[];
  is_published: boolean;
  created_at: string;
  updated_at: string;
  free_preview_limit?: number;
};

type OrderPreviewItem = {
  product_id: number;
  title: string;
  unit_price: number;
  quantity: number;
  subtotal: number;
};

type OrderPreview = {
  items: OrderPreviewItem[];
  total_amount: number;
};

type OrderPreviewMeta = {
  channels?: string[];
  hint?: string;
  can_pay?: boolean;
  item_count?: number;
};

type ProductDetail = {
  id: number;
  title: string;
  type: string;
  description: string;
  price: number;
  promoPrice?: number;
  promoExpiresAt?: string;
  heroImage: string;
  heroAssetId?: number;
  gallery: { url: string; assetId?: number }[];
  isPublished: boolean;
  createdAt: string;
  updatedAt: string;
  freePreviewLimit: number;
};

const formatCurrency = (value: number) => {
  if (!Number.isFinite(value)) {
    return '¥0.00';
  }
  return `¥${value.toFixed(2)}`;
};

const formatDate = (value: string) => {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  });
};

const mapProduct = (item: ApiProduct): ProductDetail => {
  const assetToUrl = (a?: ApiAsset | null) => resolveAssetUrl(a?.preview_url || a?.thumb_url || a?.original_url || '');
  const gallery = (item.images || [])
    .map((img) => ({ url: assetToUrl(img.asset), assetId: img.asset?.id }))
    .filter((x) => !!x.url);
  const heroImage = assetToUrl(item.cover_asset) || (gallery[0]?.url || '');
  return {
    id: item.id,
    title: item.title,
    type: item.type,
    description: item.description ?? '',
    price: item.price ?? 0,
    promoPrice: typeof item.promo_price === 'number' ? item.promo_price : undefined,
    promoExpiresAt: item.promo_expires_at ?? undefined,
    heroImage,
    heroAssetId: item.cover_asset?.id,
    gallery,
    isPublished: item.is_published ?? true,
    createdAt: item.created_at ?? '',
    updatedAt: item.updated_at ?? '',
    freePreviewLimit: Number(item.free_preview_limit ?? 0),
  };
};

export default function ProductDetailScreen() {
  const params = useLocalSearchParams<{ id?: string }>();
  const idParam = Array.isArray(params.id) ? params.id[0] : params.id;
  const productId = idParam ?? '';
  const router = useRouter();
  const { user, token } = useAuth();

  const [product, setProduct] = useState<ProductDetail | null>(null);
  const [isLoading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeIndex, setActiveIndex] = useState(-1);
  const [hasUnlocked, setUnlocked] = useState(false);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isProcessing, setProcessing] = useState(false);
  const [purchaseError, setPurchaseError] = useState<string | null>(null);
  const [payChannel, setPayChannel] = useState<PayChannel>('wechat');
  const [promoRemaining, setPromoRemaining] = useState<number>(0);
  const [recoItems, setRecoItems] = useState<{ id: number; title: string; price: number }[]>([]);
  const [fav, setFav] = useState(false);

  const loadProduct = useCallback(async () => {
    if (!productId) {
      setError('未找到对应的商品。');
      setProduct(null);
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const data = await apiRequest<ApiProduct>(`/products/${productId}`);
      if (!data) {
        throw new Error('未找到对应的商品。');
      }
      setProduct(mapProduct(data));
      setError(null);
    } catch (err) {
      setProduct(null);
      if (err instanceof ApiError && err.status === 404) {
        setError('未找到对应的商品。');
      } else {
        setError(err instanceof Error ? err.message : '商品加载失败，请稍后重试。');
      }
    } finally {
      setLoading(false);
    }
  }, [productId]);

  useEffect(() => {
    loadProduct();
  }, [loadProduct]);

  useEffect(() => {
    if (!product) return;
    addHistory({ id: product.id, title: product.title }).catch(() => {});
  }, [product]);

  // hydrate favorite state when product changes
  useEffect(() => {
    (async () => {
      if (!product) return;
      try {
        const f = await isFavorite(product.id);
        setFav(f);
      } catch {}
    })();
  }, [product]);

  // load same-type recommendations (lightweight)
  useEffect(() => {
    (async () => {
      try {
        if (!product?.type) { setRecoItems([]); return; }
        const data = await apiRequest<{ id: number; title: string; price: number }[]>('/products', {
          query: { type: product.type, limit: 6 },
        });
        const list = Array.isArray(data) ? data.filter((x) => x && x.id !== product.id) : [];
        setRecoItems(list);
      } catch { setRecoItems([]); }
    })();
  }, [product?.type, product?.id]);

  useEffect(() => {
    setActiveIndex(-1);
    setUnlocked(false);
    setPurchaseError(null);
  }, [product?.id]);

  // Load last pay channel
  useEffect(() => {
    (async () => {
      const last = await getLastPayChannel();
      if (last) setPayChannel(last);
    })();
  }, []);

  // Promo countdown
  useEffect(() => {
    if (!product?.promoExpiresAt) return;
    const end = new Date(product.promoExpiresAt).getTime();
    const tick = () => {
      const left = Math.max(0, Math.floor((end - Date.now()) / 1000));
      setPromoRemaining(left);
    };
    tick();
    const t = setInterval(tick, 1000);
    return () => clearInterval(t);
  }, [product?.promoExpiresAt]);

  const screenTitle = product?.title ?? '商品详情';
  const images = useMemo(() => {
    if (!product) {
      return [] as { url: string; assetId?: number }[];
    }
    const list = [{ url: product.heroImage, assetId: product.heroAssetId }, ...product.gallery];
    const seen = new Set<string>();
    const unique = list.filter((it) => {
      if (!it.url || seen.has(it.url)) return false;
      seen.add(it.url);
      return true;
    });
    return unique;
  }, [product]);

  const mainImage = useMemo(() => {
    if (!product) {
      return '';
    }
    if (activeIndex === -1) {
      return product.heroImage;
    }
    return product.gallery[activeIndex]?.url ?? product.heroImage;
  }, [activeIndex, product]);

  const currentAssetId = useMemo(() => {
    if (!product) return undefined;
    if (activeIndex === -1) return product.heroAssetId;
    return product.gallery[activeIndex]?.assetId ?? product.heroAssetId;
  }, [activeIndex, product]);

  const handleImagePreview = (image: string, overallIndex: number) => {
    const canView = hasUnlocked || (product ? overallIndex < product.freePreviewLimit : false);
    if (!canView) {
      Alert.alert('已锁定', '支付后可浏览更多图片与下载原图。');
      return;
    }
    setPreviewImage(image);
  };

  const handlePay = useCallback(async () => {
    if (!user) {
      const redirect = encodeRedirectParam({ pathname: '/product/[id]', params: { id: productId } });
      router.push({ pathname: '/(auth)/login', params: { redirect } });
      return;
    }

    if (user.channel !== 'customer') {
      Alert.alert('提示', '当前账号为商户角色，请使用 C 端账号登录后再购买。');
      return;
    }

    if (!token) {
      Alert.alert('提示', '登录状态已过期，请重新登录后再试。');
      const redirect = encodeRedirectParam({ pathname: '/product/[id]', params: { id: productId } });
      router.push({ pathname: '/(auth)/login', params: { redirect } });
      return;
    }

    if (!product) {
      Alert.alert('提示', '商品信息加载失败，请稍后重试。');
      return;
    }

    if (hasUnlocked) {
      Alert.alert('提示', '您已经完成支付，可直接查看原图。');
      return;
    }

    const requestItems = [{ product_id: product.id, quantity: 1 }];

    setProcessing(true);
    setPurchaseError(null);

    try {
      const { data, meta } = await apiRequestWithMeta<OrderPreview, OrderPreviewMeta>('/orders/preview', {
        method: 'POST',
        token,
        body: { items: requestItems },
      });
      const totalAmount = data?.total_amount ?? product.price ?? 0;
      const channelsRaw = Array.isArray(meta?.channels) ? meta?.channels ?? [] : [];
      const channelsText =
        channelsRaw.map((ch) => (ch === 'wechat' ? '微信支付' : ch === 'alipay' ? '支付宝支付' : ch)).join('、') ||
        '微信支付、支付宝支付';
      const hintText = meta?.hint?.trim() || '支付功能正在开发中，敬请期待。';

      Alert.alert(
        '功能开发中',
        `预计支付金额：${formatCurrency(totalAmount)}\n可用渠道：${channelsText}\n${hintText}`,
      );
    } catch (err) {
      const message = err instanceof Error ? err.message : '下单失败，请稍后重试';
      setPurchaseError(message);
      Alert.alert('支付失败', message);
    } finally {
      setProcessing(false);
    }
  }, [hasUnlocked, product, productId, router, token, user]);

  const payButtonLabel = useMemo(() => {
    if (hasUnlocked) return '已完成支付';
    if (isProcessing) return '正在创建订单...';
    if (product?.promoPrice && promoRemaining > 0) {
      return `限时价 ¥${product.promoPrice.toFixed(2)} · 支付功能开发中`;
    }
    return '支付功能开发中';
  }, [hasUnlocked, isProcessing, product?.promoPrice, promoRemaining]);

  if (isLoading) {
    return (
      <SafeAreaView style={styles.safeArea}>
        <Stack.Screen options={{ title: screenTitle }} />
        <PageHeader title={screenTitle} />
        <View style={styles.stateBox}>
          <ActivityIndicator color="#ff8fb1" />
          <Text style={styles.stateText}>正在加载商品，请稍后...</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (error || !product) {
    return (
      <SafeAreaView style={styles.safeArea}>
        <Stack.Screen options={{ title: '未找到商品' }} />
        <PageHeader title="未找到商品" />
        <View style={styles.stateBox}>
          <Text style={[styles.stateText, styles.stateTextDanger]}>
            {error ?? '抱歉，未找到对应的商品。'}
          </Text>
          <Pressable style={styles.retryButton} onPress={() => router.replace('/')}>
            <Text style={styles.retryButtonText}>返回首页</Text>
          </Pressable>
        </View>
      </SafeAreaView>
    );
  }

  const highlightItems = [
    product.type ? `服务类型：${product.type}` : null,
    `当前状态：${product.isPublished ? '上架' : '未上架'}`,
    product.updatedAt ? `最近更新：${formatDate(product.updatedAt)}` : null,
    `可免费预览：${product.freePreviewLimit} 张`,
  ].filter(Boolean) as string[];

  return (
    <SafeAreaView style={styles.safeArea}>
      <Stack.Screen options={{ title: product.title }} />
      <PageHeader title={product.title} />
      <ScrollView contentContainerStyle={styles.container} showsVerticalScrollIndicator={false}>
        <View style={styles.header}>
          <Text style={styles.title}>{product.title}</Text>
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
            <Pressable
              accessibilityRole="button"
              accessibilityLabel={fav ? '取消收藏' : '加入收藏'}
              onPress={async () => {
                if (!product) return;
                if (fav) {
                  await removeFavorite(product.id);
                  setFav(false);
                } else {
                  await addFavorite({ id: product.id, title: product.title });
                  setFav(true);
                }
              }}
              style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
            >
              <Ionicons name={fav ? 'heart' : 'heart-outline'} size={22} color={fav ? '#ff5a79' : '#9c8aa0'} />
            </Pressable>
            {product.promoPrice && promoRemaining > 0 ? (
              <View style={{ alignItems: 'flex-end' }}>
                <Text style={styles.pricePromo}>{formatCurrency(product.promoPrice)}</Text>
                <Text style={styles.priceOrigin}>{formatCurrency(product.price)}</Text>
              </View>
            ) : (
              <Text style={styles.price}>{formatCurrency(product.price)}</Text>
            )}
          </View>
        </View>

        {product.promoPrice && promoRemaining > 0 ? (
          <View style={styles.promoBanner}>
            <Text style={styles.promoText}>
              限时价 ¥{product.promoPrice.toFixed(2)} · 剩余 {Math.floor(promoRemaining / 60)
                .toString()
                .padStart(2, '0')}
              :{(promoRemaining % 60).toString().padStart(2, '0')}
            </Text>
          </View>
        ) : null}

        <View style={styles.lead}>
          <View style={styles.gallery}>
            {mainImage ? (
              <Pressable onPress={() => handleImagePreview(mainImage, activeIndex === -1 ? 0 : activeIndex + 1)}>
                <Image
                  source={{ uri: mainImage }}
                  style={styles.galleryMain}
                  contentFit="cover"
                  transition={300}
                  cachePolicy="memory-disk"
                />
              </Pressable>
            ) : null}
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.thumbRow}
            >
              {images.map((image, index) => {
                const actualIndex = index === 0 ? -1 : index - 1;
                const isActive = activeIndex === actualIndex;
                const locked = !hasUnlocked && index >= product.freePreviewLimit;
                return (
                  <Pressable
                    key={`${product.id}-${index}`}
                    style={[styles.thumb, isActive && styles.thumbActive]}
                    onPress={() => {
                      const canView = !locked;
                      if (!canView) {
                        Alert.alert('已锁定', '支付后可浏览更多图片与下载原图。');
                        return;
                      }
                      setActiveIndex(actualIndex);
                    }}
                    onLongPress={() => handleImagePreview(image.url, index)}
                  >
                    <Image source={{ uri: image.url }} style={styles.thumbImage} contentFit="cover" />
                    {locked ? (
                      <View style={styles.lockOverlay}>
                        <Ionicons name="lock-closed" size={16} color="#fff" />
                      </View>
                    ) : null}
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>

          <View style={styles.info}>
            <Text style={styles.description}>{product.description || '该套内容暂无详细介绍'}</Text>

        <View style={styles.highlights}>
          {highlightItems.map((item) => (
            <View key={item} style={styles.highlightItem}>
              <Text style={styles.highlightDot}>•</Text>
              <Text style={styles.highlightText}>{item}</Text>
            </View>
          ))}
        </View>

            <View style={styles.meta}>
              <View style={styles.metaBlock}>
                <Text style={styles.metaLabel}>服务时长</Text>
                <Text style={styles.metaValue}>下单后与您确认拍摄时间</Text>
              </View>
              <View style={styles.metaBlock}>
                <Text style={styles.metaLabel}>购买内容</Text>
                <Text style={styles.metaValue}>支付后提供精选成片与原片下载</Text>
              </View>
            </View>

            {!hasUnlocked ? (
              <View style={styles.valueBox}>
                <Text style={styles.valueTitle}>支付后您将获得：</Text>
                <Text style={styles.valueItem}>· 更多高清预览与无水印原图下载</Text>
                <Text style={styles.valueItem}>· 永久访问本套内容（账号随时可查）</Text>
                <Text style={styles.valueItem}>· 售后支持与拍摄咨询</Text>
              </View>
            ) : null}

            {purchaseError ? (
              <View style={styles.errorBadge}>
                <Text style={styles.errorText}>{purchaseError}</Text>
              </View>
            ) : null}

            {/* 支付方式选择（记住上次选择） */}
            <View style={styles.payOptionsRow}>
              <Pressable
                accessibilityRole="button"
                accessibilityLabel="微信支付"
                onPress={() => setPayChannel('wechat')}
                style={[styles.payOption, payChannel === 'wechat' && styles.payOptionActive]}
              >
                <View style={styles.payOptionContent}>
                  <AntDesign name="wechat" size={22} color="#1AAD19" />
                  <Text style={styles.payOptionLabel}>微信</Text>
                </View>
              </Pressable>
              <Pressable
                accessibilityRole="button"
                accessibilityLabel="支付宝"
                onPress={() => setPayChannel('alipay')}
                style={[styles.payOption, payChannel === 'alipay' && styles.payOptionActive]}
              >
                <View style={styles.payOptionContent}>
                  <AntDesign name="alipay-circle" size={22} color="#1677FF" />
                  <Text style={styles.payOptionLabel}>支付宝</Text>
                </View>
              </Pressable>
            </View>

            <Pressable
              style={({ pressed }) => [
                styles.payButton,
                pressed && !hasUnlocked && !isProcessing && styles.payButtonPressed,
                (hasUnlocked || isProcessing) && styles.payButtonDisabled,
              ]}
              onPress={handlePay}
              disabled={hasUnlocked || isProcessing}
            >
              <Text style={styles.payButtonText}>{payButtonLabel}</Text>
            </Pressable>

            {/* 相似推荐（同类型） */}
            {product.type && recoItems.length > 0 ? (
              <View style={styles.recoBox}>
                <Text style={styles.recoTitle}>你可能还喜欢</Text>
                <ScrollView
                  horizontal
                  showsHorizontalScrollIndicator={false}
                  contentContainerStyle={{ gap: 10 }}
                >
                  {recoItems.map((it) => (
                    <Pressable
                      key={it.id}
                      style={styles.recoCard}
                      onPress={() =>
                        router.push({ pathname: '/c/product/[id]', params: { id: String(it.id) } })
                      }
                    >
                      <Text style={styles.recoName} numberOfLines={1}>
                        {it.title}
                      </Text>
                      <Text style={styles.recoPrice}>{formatCurrency(it.price)}</Text>
                    </Pressable>
                  ))}
                </ScrollView>
              </View>
            ) : null}
          </View>
        </View>
      </ScrollView>

      <Modal
        visible={!!previewImage}
        transparent
        animationType="fade"
        onRequestClose={() => setPreviewImage(null)}
      >
        <Pressable style={styles.previewBackdrop} onPress={() => setPreviewImage(null)}>
          <Pressable
            style={styles.previewFrame}
            onLongPress={() => {
              if (!hasUnlocked) {
                Alert.alert('提示', '支付后可下载原图。');
                return;
              }
              if (!currentAssetId || !token) {
                return;
              }
              const url = `${API_ORIGIN}/api/v1/assets/${currentAssetId}/original?token=${encodeURIComponent(token)}`;
              Linking.openURL(url).catch(() => Alert.alert('提示', '请检查网络或稍后重试'));
            }}
          >
            {previewImage ? (
              <Image source={{ uri: previewImage }} style={styles.previewImage} contentFit="contain" />
            ) : null}
          </Pressable>
        </Pressable>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff7fb',
  },
  container: {
    padding: 24,
    gap: 24,
  },
  stateBox: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 16,
    paddingHorizontal: 24,
  },
  stateText: {
    fontSize: 14,
    color: '#5f4d5c',
    textAlign: 'center',
  },
  stateTextDanger: {
    color: '#d64f7c',
  },
  retryButton: {
    paddingHorizontal: 18,
    paddingVertical: 10,
    borderRadius: 999,
    backgroundColor: '#ff8fb1',
  },
  retryButtonText: {
    color: '#2f1f2b',
    fontWeight: '600',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  title: {
    flex: 1,
    fontSize: 22,
    fontWeight: '700',
    color: '#2f1f2b',
    marginRight: 12,
  },
  price: {
    fontSize: 20,
    fontWeight: '700',
    color: '#d66a8a',
  },
  pricePromo: {
    fontSize: 20,
    fontWeight: '800',
    color: '#d66a8a',
  },
  priceOrigin: {
    fontSize: 12,
    color: '#8b7486',
    textDecorationLine: 'line-through',
  },
  lead: {
    gap: 18,
  },
  gallery: {
    gap: 12,
  },
  galleryMain: {
    width: '100%',
    height: 280,
    borderRadius: 24,
  },
  thumbRow: {
    gap: 10,
    paddingVertical: 4,
  },
  thumb: {
    borderRadius: 14,
    borderWidth: 2,
    borderColor: 'transparent',
  },
  thumbActive: {
    borderColor: 'rgba(214,106,138,0.6)',
  },
  thumbImage: {
    width: 72,
    height: 72,
    borderRadius: 12,
  },
  lockOverlay: {
    position: 'absolute',
    top: 6,
    right: 6,
    width: 22,
    height: 22,
    borderRadius: 11,
    backgroundColor: 'rgba(0,0,0,0.55)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  info: {
    gap: 12,
    padding: 18,
    borderRadius: 24,
    backgroundColor: 'rgba(255,255,255,0.95)',
    borderWidth: 1,
    borderColor: 'rgba(220,195,208,0.4)',
  },
  description: {
    fontSize: 14,
    lineHeight: 22,
    color: '#5f4d5c',
  },
  promoBanner: {
    marginTop: 10,
    marginBottom: 6,
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 12,
    backgroundColor: 'rgba(255,143,177,0.15)',
    alignSelf: 'flex-start',
  },
  promoText: {
    color: '#d66a8a',
    fontWeight: '700',
  },
  payOptionsRow: {
    flexDirection: 'row',
    gap: 10,
    marginTop: 6,
    marginBottom: 6,
  },
  payOption: {
    borderRadius: 999,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderWidth: 1,
    borderColor: '#eee',
    backgroundColor: '#faf7fb',
  },
  payOptionActive: {
    borderColor: '#ff8fb1',
    backgroundColor: '#ffeaf3',
  },
  payOptionContent: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  payOptionLabel: {
    fontSize: 13,
    color: '#403245',
    fontWeight: '600',
  },
  highlights: {
    gap: 8,
  },
  highlightItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  highlightDot: {
    color: '#d66a8a',
    fontSize: 16,
  },
  highlightText: {
    flex: 1,
    color: '#6a566a',
    fontSize: 13,
  },
  meta: {
    flexDirection: 'row',
    gap: 12,
  },
  metaBlock: {
    flex: 1,
    gap: 4,
  },
  metaLabel: {
    fontSize: 11,
    letterSpacing: 2,
    color: '#8b7486',
  },
  metaValue: {
    fontSize: 13,
    fontWeight: '600',
    color: '#403245',
  },
  valueBox: {
    marginTop: 10,
    padding: 12,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: 'rgba(214,106,138,0.18)',
    backgroundColor: 'rgba(255,143,177,0.08)',
    gap: 4,
  },
  valueTitle: {
    fontSize: 13,
    fontWeight: '700',
    color: '#403245',
  },
  valueItem: {
    fontSize: 12,
    color: '#6a566a',
  },
  recoBox: {
    marginTop: 10,
    marginBottom: 6,
    gap: 8,
  },
  recoTitle: {
    fontSize: 15,
    fontWeight: '700',
    color: '#403245',
  },
  recoCard: {
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#eee',
    backgroundColor: '#fff',
    minWidth: 160,
  },
  recoName: { fontSize: 13, color: '#403245', fontWeight: '600' },
  recoPrice: { marginTop: 6, fontSize: 12, color: '#6a566a' },
  errorBadge: {
    borderRadius: 12,
    borderWidth: 1,
    borderColor: 'rgba(214,79,124,0.24)',
    backgroundColor: 'rgba(214,79,124,0.08)',
    paddingHorizontal: 14,
    paddingVertical: 10,
  },
  errorText: {
    fontSize: 13,
    color: '#d64f7c',
  },
  payButton: {
    marginTop: 4,
    borderRadius: 999,
    paddingVertical: 12,
    backgroundColor: '#ff8fb1',
    alignItems: 'center',
  },
  payButtonPressed: {
    backgroundColor: '#ff6a9b',
  },
  payButtonDisabled: {
    backgroundColor: 'rgba(255,143,177,0.4)',
  },
  payButtonText: {
    color: '#2f1f2b',
    fontWeight: '600',
    fontSize: 15,
  },
  previewBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.85)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  previewFrame: {
    width: '90%',
    height: '70%',
    borderRadius: 16,
    overflow: 'hidden',
  },
  previewImage: {
    width: '100%',
    height: '100%',
  },
});

















